package com.sxfq.loansupermarket.backsystem.modular.tcCenter.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.DoctorDiagnosisInfo;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.TongJiInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.ITcRevisitService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * tctc回访
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/tcRevisit")
public class TcRevisitController extends BaseController {
    @Autowired
    ITcRevisitService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/tcCenter/consultant/";

    /**
     * 跳转到tc回访
     */
    @RequestMapping("")
    public String tc_visits(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList",  ShiroKit.getUser().getTcList());
        model.addAttribute("loginName", ShiroKit.getUser().getAccount());
        return PREFIX + "tc_revisits.html";
    }

    /**
     * 跳转到前台tc回访
     */
    @RequestMapping("/qttc_visits")
    public String qttc_visits(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList",  ShiroKit.getUser().getTcList());
        return PREFIX + "qttc_revisits.html";
    }

    /**
     * 跳转到市场tc回访
     */
    @RequestMapping("/res_visits")
    public String res_visits(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList",  ShiroKit.getUser().getTcList());
        return PREFIX + "res_revisits.html";
    }

    @RequestMapping(value = "/to_addsf")
    public String to_addsf(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "addsf.html";
    }

    @RequestMapping(value = "/to_addjg")
    public String to_addjg(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "addjg.html";
    }

    @RequestMapping(value = "/addjg", method = RequestMethod.POST)
    @ResponseBody
    public int addjg(String remarks, String title, Model model) {
        String sql = "insert into tc_follow_results_template (title,remarks,user) value ('" + title + "','" + remarks + "','" + ShiroKit.getUser().getAccount() + "')";
        return sqlMapper.insert(sql);
    }

    /**
     * TC回访
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object tcInfoList(SearchTcRevisitInfo info, HttpServletRequest request) {
        if(info.getAbbreviation() ==null || info.getAbbreviation() == "" || info.getAbbreviation() =="null"){
            return null;
        }else{
            Page<TcRevisitInfo> page = new PageFactory<TcRevisitInfo>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<TcRevisitInfo> list = service.selectPageListByRevisit(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByRevisit(page, info);
                }
                page.setTotal(service.getQueryPagesRevisitCount(page, info));
                page.setRecords(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    @RequestMapping(value = "/getSfList", method = RequestMethod.POST)
    @ResponseBody
    public List<SfInfo> getSfList() {
        List<SfInfo> list = service.getSfList();
        return list;
    }

    @RequestMapping(value = "/getJgList", method = RequestMethod.POST)
    @ResponseBody
    public List<SfInfo> getJgList() {
        List<SfInfo> list = service.getJgList();
        return list;
    }

    //删除tc回访模板
    @RequestMapping(value = "/deleteSfById", method = RequestMethod.POST)
    @ResponseBody
    public int deleteSfById(String id) throws Exception {
        String sql = "delete from tc_follow_template where id='" + id + "'";
        return sqlMapper.delete(sql);
    }

    //删除tc回访结果模板
    @RequestMapping(value = "/deleteJgById", method = RequestMethod.POST)
    @ResponseBody
    public int deleteJgById(String id) throws Exception {
        String sql = "delete from tc_follow_results_template where id='" + id + "'";
        return sqlMapper.delete(sql);
    }

    //删除tc回访
    @RequestMapping(value = "/delete_tcFollow", method = RequestMethod.POST)
    @ResponseBody
    public int delete_tcFollow(String ids) throws Exception {
        String sql = "delete from return_tc_visit_info where id='" + ids + "'";
        return sqlMapper.delete(sql);
    }

    /**
     * 跳转到tc看诊 传客户ID 和预约ID 和回访时间
     */
    @RequestMapping(value = "/tc_follow/{ids}")
    public String tc_follow(@PathVariable String ids, Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String customerId = ids.split(",")[2];
        String revisitTime = ids.split(",")[3];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(revisitTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql1 = "select t2.customer_name as customerName,t2.reservations_id as reservationsId,t2.medical_record_number as medicalRecordNumber,t2.doctor as doctor," +
                "  (CASE t2.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,t2.customer_age as customerAge,t2.customer_phone as customerPhone ,t2.field_tc as fieldTc,t2.one_channel as oneChannel,left(t1.first_visit_date,19) as firstVisitDate" +
                " from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t2 left join reservations_info t1 on t1.id = t2.reservations_id where t2.id='" + customerId + "' limit 1";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        String sql2 = "select r.id,r.reservations_id,r.customer_id,r.revisit,left(r.revisit_time,10) as revisitTime,r.outpatient_name," +
                " r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where r.revisit_time ='" + revisitTime + "' and id='" + id + "' limit 1";
        TcRevisitsInfo tcRevisitInfo = sqlMapper.selectOne(sql2, TcRevisitsInfo.class);
        //tc回访记录
        String sql4 = "select r.id,r.reservations_id,r.customer_id,r.create_name,r.revisit,r.revisit_time,r.create_time,r.outpatient_name,r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where r.reservations_id ='" + reservationsId + "' order by revisit_time desc";
        List<TcRevisitsInfo> tcRevisitInfoList = sqlMapper.selectList(sql4, TcRevisitsInfo.class);
        for (TcRevisitsInfo info1 : tcRevisitInfoList) {
            if (info1.getRevisitTime() != "" && info1.getRevisitTime() != null) {
                info1.setRevisitTime(info1.getRevisitTime().substring(0, 11));
            }
        }
        //病历记录
        String sql5 = "select left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,left(t.arrival_time,19) as arrivalTime,t.id as id," +
                "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.remarks_reservation as remarksReservation," +
                "t.arrival_status as arrivalStatus," +
                "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status,t.appointment_pay_service as appointmentPayService," +
                "t1.zhushu as zhushu,t1.remarkss as remarkss,t1.doctor_advice as doctorAdvice from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t " +
                "left join case_info t1 on t.id=t1.customer_id where t.reservations_id='" + reservationsId + "' " +
                " and t.arrival_status in (1,2,3,4,5,6,9,10) and t1.arrival_store='"+ShiroKit.getUser().getOutpatientName()+"' " +
                " order by start_time desc";
        List<DoctorDiagnosisInfo> DoctorDiagnosisInfoList = sqlMapper.selectList(sql5, DoctorDiagnosisInfo.class);
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("tcRevisitInfoList", tcRevisitInfoList);  //tc回访记录
        model.addAttribute("DoctorDiagnosisInfoList", DoctorDiagnosisInfoList); //就诊记录
        model.addAttribute("tcRevisitInfo", tcRevisitInfo);
        model.addAttribute("customerId", customerId);
        model.addAttribute("createName", ShiroKit.getUser().getAccount());  //创建人
        model.addAttribute("arrivalStore", ShiroKit.getUser().getOutpatientName());  //门店
        return PREFIX + "tc_follow.html";
    }

    /**
     * 跳转到tc看诊 传客户ID 和预约ID 和回访时间
     */
    @RequestMapping(value = "/tc_followss/{ids}")
    public String tc_follows(@PathVariable String ids, Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String customerId = ids.split(",")[2];
        String revisitTime = ids.split(",")[3];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(revisitTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql1 = "select t2.customer_name as customerName,t2.reservations_id as reservationsId,t2.medical_record_number as medicalRecordNumber,t2.doctor as doctor," +
                "  (CASE t2.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,t2.customer_age as customerAge,t2.customer_phone as customerPhone ,t2.field_tc as fieldTc,t2.one_channel as oneChannel,left(t1.first_visit_date,19) as firstVisitDate" +
                " from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t2 left join reservations_info t1 on t1.id = t2.reservations_id where t2.id='" + customerId + "' limit 1";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        String sql2 = "select r.id,r.reservations_id,r.customer_id,r.revisit,left(r.revisit_time,10) as revisitTime,r.outpatient_name," +
                " r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where  r.revisit_time ='" + revisitTime + "' and id='" + id + "' limit 1";
        TcRevisitsInfo tcRevisitInfo = sqlMapper.selectOne(sql2, TcRevisitsInfo.class);
        //tc回访记录
        String sql4 = "select r.id,r.reservations_id,r.customer_id,r.create_name,r.revisit,r.revisit_time,r.create_time,r.outpatient_name,r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where r.reservations_id ='" + reservationsId + "' order by revisit_time desc";
        List<TcRevisitsInfo> tcRevisitInfoList = sqlMapper.selectList(sql4, TcRevisitsInfo.class);
        for (TcRevisitsInfo info1 : tcRevisitInfoList) {
            if (info1.getRevisitTime() != "" && info1.getRevisitTime() != null) {
                info1.setRevisitTime(info1.getRevisitTime().substring(0, 11));
            }
        }
        //病历记录
        String sql5 = "select left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,left(t.arrival_time,19) as arrivalTime,t.id as id," +
                "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.remarks_reservation as remarksReservation," +
                "t.arrival_status as arrivalStatus," +
                "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status,t.appointment_pay_service as appointmentPayService," +
                "t1.zhushu as zhushu,t1.remarkss as remarkss,t1.doctor_advice as doctorAdvice from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t " +
                "left join case_info t1 on t.id=t1.customer_id where t.reservations_id='" + reservationsId + "' " +
                " and t.arrival_status in (1,2,3,4,5,6,9,10) and t1.arrival_store='"+ShiroKit.getUser().getOutpatientName()+"' " +
                " order by start_time desc";
        List<DoctorDiagnosisInfo> DoctorDiagnosisInfoList = sqlMapper.selectList(sql5, DoctorDiagnosisInfo.class);
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("tcRevisitInfoList", tcRevisitInfoList);  //tc回访记录
        model.addAttribute("DoctorDiagnosisInfoList", DoctorDiagnosisInfoList); //就诊记录
        model.addAttribute("tcRevisitInfo", tcRevisitInfo);
        model.addAttribute("customerId", customerId);
        model.addAttribute("createName", ShiroKit.getUser().getAccount());  //创建人
        model.addAttribute("arrivalStore", ShiroKit.getUser().getOutpatientName());  //门店
        return PREFIX + "tc_followss.html";
    }

    /**
     * 查看tc回访详情
     */
    @RequestMapping(value = "/tc_lookfollow/{ids}")
    public String tc_lookfollow(@PathVariable String ids, Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String customerId = ids.split(",")[2];
        String revisitTime = ids.split(",")[3];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(revisitTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql1 = "select t2.customer_name as customerName,t2.reservations_id as reservationsId,t2.medical_record_number as medicalRecordNumber,t2.doctor as doctor," +
                "  (CASE t2.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,t2.customer_age as customerAge,t2.customer_phone as customerPhone ,t2.field_tc as fieldTc,t2.one_channel as oneChannel,left(t1.first_visit_date,19) as firstVisitDate" +
                " from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t2 left join reservations_info t1 on t1.id = t2.reservations_id where t2.id='" + customerId + "' limit 1";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        String sql2 = "select r.id,r.reservations_id,r.customer_id,r.revisit,left(r.revisit_time,10) as revisitTime,r.outpatient_name," +
                " r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where  r.revisit_time ='" + revisitTime + "' and id='" + id + "' limit 1";
        TcRevisitsInfo tcRevisitInfo = sqlMapper.selectOne(sql2, TcRevisitsInfo.class);
        //tc回访记录
        String sql4 = "select r.id,r.reservations_id,r.customer_id,r.create_name,r.revisit,r.revisit_time,r.create_time,r.outpatient_name,r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where r.reservations_id ='" + reservationsId + "' order by revisit_time desc";
        List<TcRevisitsInfo> tcRevisitInfoList = sqlMapper.selectList(sql4, TcRevisitsInfo.class);
        for (TcRevisitsInfo info1 : tcRevisitInfoList) {
            if (info1.getRevisitTime() != "" && info1.getRevisitTime() != null) {
                info1.setRevisitTime(info1.getRevisitTime().substring(0, 11));
            }
        }
        //病历记录
        String sql5 = "select left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,left(t.arrival_time,19) as arrivalTime,t.id as id," +
                "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.remarks_reservation as remarksReservation," +
                "t.arrival_status as arrivalStatus," +
                "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status,t.appointment_pay_service as appointmentPayService," +
                "t1.zhushu as zhushu,t1.remarkss as remarkss,t1.doctor_advice as doctorAdvice from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t " +
                "left join case_info t1 on t.id=t1.customer_id where t.reservations_id='" + reservationsId + "' " +
                " and t.arrival_status in (1,2,3,4,5,6,9,10) and t1.arrival_store='"+ShiroKit.getUser().getOutpatientName()+"' " +
                " order by start_time desc";
        List<DoctorDiagnosisInfo> DoctorDiagnosisInfoList = sqlMapper.selectList(sql5, DoctorDiagnosisInfo.class);
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("tcRevisitInfoList", tcRevisitInfoList);  //tc回访记录
        model.addAttribute("DoctorDiagnosisInfoList", DoctorDiagnosisInfoList); //就诊记录
        model.addAttribute("tcRevisitInfo", tcRevisitInfo);
        model.addAttribute("customerId", customerId);
        model.addAttribute("createName", ShiroKit.getUser().getAccount());  //创建人
        model.addAttribute("arrivalStore", ShiroKit.getUser().getOutpatientName());  //门店
        return PREFIX + "tc_lookefollow.html";
    }

    /**
     * 查看tc回访详情
     */
    @RequestMapping(value = "/tc_lookfollowList/{ids}")
    public String tc_lookfollowList(@PathVariable String ids, Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String customerId = ids.split(",")[2];
        String revisitTime = ids.split(",")[3];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(revisitTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql1 = "select t2.customer_name as customerName,t2.reservations_id as reservationsId,t2.medical_record_number as medicalRecordNumber,t2.doctor as doctor," +
                "  (CASE t2.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,t2.customer_age as customerAge,t2.customer_phone as customerPhone ,t2.field_tc as fieldTc,t2.one_channel as oneChannel,left(t1.first_visit_date,19) as firstVisitDate" +
                " from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t2 left join reservations_info t1 on t1.id = t2.reservations_id where t2.id='" + customerId + "' limit 1";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        String sql2 = "select r.id,r.reservations_id,r.customer_id,r.revisit,left(r.revisit_time,10) as revisitTime,r.outpatient_name," +
                " r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where  r.revisit_time ='" + revisitTime + "' and id='" + id + "' limit 1";
        TcRevisitsInfo tcRevisitInfo = sqlMapper.selectOne(sql2, TcRevisitsInfo.class);
        //tc回访记录
        String sql4 = "select r.id,r.reservations_id,r.customer_id,r.create_name,r.revisit,r.revisit_time,r.create_time,r.outpatient_name,r.revisit_content,r.tc_name,r.revisit_status,r.remarks,r.consumption_status,r.follow_status from return_tc_visit_info r " +
                " where r.reservations_id ='" + reservationsId + "' order by revisit_time desc";
        List<TcRevisitsInfo> tcRevisitInfoList = sqlMapper.selectList(sql4, TcRevisitsInfo.class);
        for (TcRevisitsInfo info1 : tcRevisitInfoList) {
            if (info1.getRevisitTime() != "" && info1.getRevisitTime() != null) {
                info1.setRevisitTime(info1.getRevisitTime().substring(0, 11));
            }
        }
        //病历记录
        String sql5 = "select left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,left(t.arrival_time,19) as arrivalTime,t.id as id," +
                "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.remarks_reservation as remarksReservation," +
                "t.arrival_status as arrivalStatus," +
                "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status,t.appointment_pay_service as appointmentPayService," +
                "t1.zhushu as zhushu,t1.remarkss as remarkss,t1.doctor_advice as doctorAdvice from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t " +
                "left join case_info t1 on t.id=t1.customer_id where t.reservations_id='" + reservationsId + "' " +
                " and t.arrival_status in (1,2,3,4,5,6,9,10) and t1.arrival_store='"+ShiroKit.getUser().getOutpatientName()+"' " +
                " order by start_time desc";
        List<DoctorDiagnosisInfo> DoctorDiagnosisInfoList = sqlMapper.selectList(sql5, DoctorDiagnosisInfo.class);
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("tcRevisitInfoList", tcRevisitInfoList);  //tc回访记录
        model.addAttribute("DoctorDiagnosisInfoList", DoctorDiagnosisInfoList); //就诊记录
        model.addAttribute("tcRevisitInfo", tcRevisitInfo);
        model.addAttribute("customerId", customerId);
        model.addAttribute("createName", ShiroKit.getUser().getAccount());  //创建人
        model.addAttribute("arrivalStore", ShiroKit.getUser().getOutpatientName());  //门店
        return PREFIX + "tc_lookefollowList.html";
    }

    @RequestMapping(value = "/addsf", method = RequestMethod.POST)
    @ResponseBody
    public int addsf(String remarks, String title, Model model) {
        String sql = "insert into tc_follow_template (title,remarks,user) value ('" + title + "','" + remarks + "','" + ShiroKit.getUser().getAccount() + "')";
        return sqlMapper.insert(sql);
    }

    /**
     * 计划回访
     */
    @RequestMapping(value = "/addTcContent2", method = RequestMethod.POST)
    @ResponseBody
    public int addTcContent2(String customerId,String tcName,String followStatus, String consumptionStatus, String revisitContent, String revisitTime,
                             String remarks, String reservationsId, String arrivalStore, String createName, String revisit) {
        String sql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time,create_time," +
                "outpatient_name,remarks,revisit_content,create_name,follow_status,consumption_status,revisit_status) values ('" + reservationsId
                + "','" + customerId + "','" + revisit + "','" + revisitTime + "','" + DateTimeKit.now()+ "','" + ShiroKit.getUser().getOutpatientName()
                + "','" + remarks + "','" + revisitContent + "','" + ShiroKit.getUser().getAccount()
                + "','" + followStatus + "','" + consumptionStatus + "',1)";
        String updsql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set first_return_settings=1, follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "'," +
                "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updsql);
        return sqlMapper.insert(sql);
    }

    /**
     * 回访完成
     */
    @RequestMapping(value = "/addTcContentOver", method = RequestMethod.POST)
    @ResponseBody
    public int addTcContentOver(String customerId,String tcName,String followStatus, String consumptionStatus, String revisitContent, String revisitTime,
                             String remarks, String reservationsId, String arrivalStore, String createName, String revisit) {
        String sql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time,create_time," +
                "outpatient_name,remarks,revisit_content,create_name,follow_status,consumption_status,revisit_status,update_time) values ('" + reservationsId
                + "','" + customerId + "','" + revisit + "','" + revisitTime + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName()
                + "','" + remarks + "','" + revisitContent + "','" + ShiroKit.getUser().getAccount()
                + "','" + followStatus + "','" + consumptionStatus + "',2,'" + DateTimeKit.now() + "')";
        String updsql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set first_return_settings=1, follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "'," +
                "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updsql);
        return sqlMapper.insert(sql);
    }

    /**
     * 跳转到tc再tc回访
     */
    @RequestMapping("/tc_followUp")
    public String tc_followUp(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "tc_followUp.html";
    }

    /**
     * tc回访数据列表
     */
    @RequestMapping(value = "/TcFollowTableList/{reservationsId}")
    @ResponseBody
    public List<TcRevisitsInfo> TcFollowTableList(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select t.id as id,t.customer_id as customerId,t.reservations_id as reservationsId,t.revisit as revisit,t.revisit_time as revisitTime," +
                "t.update_time as updateTime,t.create_time as createTime,t.outpatient_name as outpatientName,t.revisit_content as revisitContent,t.tc_name as tcName,t.remarks as remarks," +
                "t.revisit_status as revisitStatus,t.create_name as createName,r.customer_name as customer_Name,r.arrival_store as arrivalStore,r.field_tc as fieldTc,t.consumption_status,t.follow_status from return_tc_visit_info t " +
                "left join " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " r on t.customer_id = r.id where t.reservations_id='" + reservationsId + "' order by t.revisit_time desc";
        List<TcRevisitsInfo> list = sqlMapper.selectList(sql, TcRevisitsInfo.class);
        return list;
    }

    /**
     * 修改回访计划
     */
    @RequestMapping(value = "/updateTcContent", method = RequestMethod.POST)
    @ResponseBody
    public int updateTcContent(String tcName, String createName,String followStatus, String consumptionStatus,
                               String revisitTime, String revisitContent, String tcVisitId,
                               String remarks, String customerId, String reservationsId, String revisit) {
        String updatesql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "' where reservations_id='" + reservationsId + "'";
        String sql = "update return_tc_visit_info set tc_name='" + tcName + "',create_name='" + createName
                + "',revisit_time='" + revisitTime + "',revisit_content='" + revisitContent
                + "',remarks='" + remarks + "',revisit='" + revisit + "',follow_status='"+followStatus+"',consumption_status='"+consumptionStatus+"' where reservations_id='" + reservationsId + "' and id='" + tcVisitId + "'";
        sqlMapper.update(updatesql);
        return sqlMapper.update(sql);
    }

    /**
     * 跳转到tc再tc回访
     */
    @RequestMapping("/tc_followUp2")
    public String tc_followUp2(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "tc_followUp2.html";
    }

    @RequestMapping(value = "/getSfById", method = RequestMethod.POST)
    @ResponseBody
    public SfInfo getSfById(String id, Model model) {
        SfInfo info = service.getSfById(id);
        return info;
    }

    @RequestMapping(value = "/getJgById", method = RequestMethod.POST)
    @ResponseBody
    public SfInfo getJgById(String id, Model model) {
        SfInfo info = service.getJgById(id);
        return info;
    }

    /**
     * 添加tc回访再
     *
     * @return
     */
    @RequestMapping(value = "/addTcContentz", method = RequestMethod.POST)
    @ResponseBody
    public int addTcContent(String customerId, String revisitTime,String revisit,String createName,String followStatus, String consumptionStatus,
                            String remarks,String revisitContent, String reservationsId, String arrivalStore) {
        String sql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                "outpatient_name,remarks,create_name,revisit_status,follow_status,consumption_status) values ('" + reservationsId
                + "','" + customerId + "','" + revisit + "','" + revisitTime + "','" + ShiroKit.getUser().getOutpatientName()
                + "','" + remarks + "','" + createName + "',1,'" + followStatus + "','" + consumptionStatus + "')";
        String updatesql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updatesql);
        return sqlMapper.insert(sql);
    }

    /**
     * 修改完成tc回访
     */
    @RequestMapping(value = "/updateTcContent1", method = RequestMethod.POST)
    @ResponseBody
    public int updateTcContent1(String tcName, String createName,String followStatus, String consumptionStatus,
                                String revisitTime, String revisitContent, String tcVisitId,
                                String remarks, String reservationsId, String revisit) {
        String sql = "update return_tc_visit_info set tc_name='" + tcName + "',create_name='" + createName
                + "',revisit_time='" + revisitTime + "',revisit_content='" + revisitContent
                + "',remarks='" + remarks + "',revisit='" + revisit + "',revisit_status='2',update_time='"+DateTimeKit.now()+"',follow_status='"+followStatus+"',consumption_status='"+consumptionStatus+"' where reservations_id='" + reservationsId + "' and id='" + tcVisitId + "'";
        String updatesql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updatesql);
        return sqlMapper.update(sql);
    }

    /**
     * 修改完成tc回访
     */
    @RequestMapping(value = "/updateTcContentOver1", method = RequestMethod.POST)
    @ResponseBody
    public int updateTcContentOver1(String tcName, String createName,String followStatus, String consumptionStatus,
                                String revisitTime, String revisitContent, String tcVisitId,
                                String remarks, String reservationsId, String revisit) {
        String sql = "update return_tc_visit_info set tc_name='" + tcName + "',create_name='" + createName
                + "',revisit_time='" + revisitTime + "',revisit_content='" + revisitContent + "',remarks='" + remarks + "',revisit='" + revisit + "',revisit_status='2',follow_status='"+followStatus+"',consumption_status='"+consumptionStatus+"' where reservations_id='" + reservationsId + "' and id='" + tcVisitId + "'";
        String updatesql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updatesql);
        return sqlMapper.update(sql);
    }

    /**
     * 取消回访
     */
    @RequestMapping(value = "/updateTcContent2", method = RequestMethod.POST)
    @ResponseBody
    public int updateTcContent2(String tcName, String createName,String followStatus, String consumptionStatus,
                                String revisitTime, String revisitContent, String tcVisitId,
                                String remarks, String reservationsId, String revisit) {
        String sql = "update return_tc_visit_info set tc_name='" + tcName + "',create_name='" + createName
                + "',revisit_time='" + revisitTime + "',revisit_content='" + revisitContent
                + "',remarks='" + remarks + "',revisit='" + revisit + "',revisit_status=4,follow_status='"+followStatus+"',consumption_status='"+consumptionStatus+"' where reservations_id='" + reservationsId + "' and id='" + tcVisitId + "'";
        String updatesql = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " set follow_status='" + followStatus + "',consumption_status='" + consumptionStatus + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updatesql);
        return sqlMapper.update(sql);
    }

    /**
     * 表格中 修改  保存在tc回访
     */
    @RequestMapping(value = "/addTcContents", method = RequestMethod.POST)
    @ResponseBody
    public int addTcContents(String customerId, String tcName, String revisitTime,String followStatus, String consumptionStatus,
                             String remarks, String reservationsId, String arrivalStore, String createName, String revisit) {
        String sql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                "outpatient_name,tc_name,remarks,create_name,revisit_status,follow_status,consumption_status) values ('" + reservationsId
                + "','" + customerId + "','" + revisit + "','" + revisitTime + "','" + ShiroKit.getUser().getOutpatientName()
                + "','" + tcName + "','" + remarks + "','" + createName + "','" + 1 + "','" + followStatus + "','" + consumptionStatus + "')";
        sqlMapper.insert(sql);
        String insertInto = "update " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " a set follow_status='"+followStatus+"',consumption_status='"+consumptionStatus+"' where reservations_id='" + reservationsId + "'";
        return sqlMapper.update(insertInto);
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/total", method = RequestMethod.GET)
    @ResponseBody
    public List<TongJiInfo> change(String reach,String startRevisitTime,String startTime,String endTime,String startUpdateTime,String endUpdateTime,String followStatus,String consumptionStatus,
                                   String endRevisitTime, String revisit) throws Exception {
        String contitionInfo = " and t.outpatient_name='"+ShiroKit.getUser().getOutpatientName()+"' ";
        if (StringUtils.isNotBlank(startRevisitTime)) {
            contitionInfo += " and t.revisit_time >='" + startRevisitTime + "' ";
        }
        if (StringUtils.isNotBlank(endRevisitTime)) {
            contitionInfo += " and t.revisit_time <='" + endRevisitTime + "' ";
        }
        if (StringUtils.isNotBlank(startTime)) {
            contitionInfo += " and t.create_time >='" + startTime + "' ";
        }
        if (StringUtils.isNotBlank(endTime)) {
            contitionInfo += " and t.create_time <='" + endTime + "' ";
        }
        if (StringUtils.isNotBlank(startUpdateTime)) {
            contitionInfo += " and t.update_time >='" + startUpdateTime + "' ";
        }
        if (StringUtils.isNotBlank(endUpdateTime)) {
            contitionInfo += " and t.update_time <='" + endUpdateTime + "' ";
        }
        if (StringUtils.isNotBlank(revisit)) {
            contitionInfo += " and t.revisit='" + revisit + "' ";
        }
        if (StringUtils.isNotBlank(followStatus)) {
            contitionInfo += " and t.follow_status='" + followStatus + "' ";
        }
        if (StringUtils.isNotBlank(consumptionStatus)) {
            contitionInfo += " and t.consumption_status='" + consumptionStatus + "' ";
        }
        if (StringUtils.isNotBlank(reach)) {
            contitionInfo += "   and (t1.customer_name like CONCAT('%','" + reach + "','%') or t1.customer_phone like CONCAT('%','" + reach + "','%') or " +
                    "            t1.wechat_number like CONCAT('%','" + reach + "','%') or t1.medical_record_number like CONCAT('%','" + reach + "','%') " +
                    "            or t1.customer_phone2 like CONCAT('%','" + reach + "','%') or t1.szm like CONCAT('%','" + reach + "','%') or t.tc_name like CONCAT('%','" + reach + "','%')) ";
        }
        contitionInfo += " group by t.id";
        String sql = "select count(*) as countNum from (select t.id from return_tc_visit_info t," + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t1 where t.customer_id = t1.id " + contitionInfo + ") t " +
                " union all select count(*) as countNum from (select t.id from return_tc_visit_info t , " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t1 where t.customer_id = t1.id and t.revisit_status ='1' " + contitionInfo + ") t" +

                " union all  select count(*) as countNum from (select t.id from return_tc_visit_info t , " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t1 where t.customer_id = t1.id and t.revisit_status ='2' " + contitionInfo + ") t" +

                " union all  select count(*) as countNum from (select t.id from return_tc_visit_info t , " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t1 where t.customer_id = t1.id and t.revisit_status ='3' " + contitionInfo + ") t" +

                " union all  select count(*) as countNum from (select t.id from return_tc_visit_info t , " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t1 where t.customer_id = t1.id and t.revisit_status ='4' " + contitionInfo + ") t";
        List<TongJiInfo> tongJiInfoList1 = sqlMapper.selectList(sql, TongJiInfo.class);
        return tongJiInfoList1;
    }
}